'use client';

import { useState, useEffect } from 'react';
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  TrendingUp,
  Zap,
  Clock,
  Activity,
  BarChart3,
  PieChart as PieChartIcon,
} from 'lucide-react';
import { PERFORMANCE_METRICS } from '@/constants';

/**
 * 性能数据可视化组件
 * 使用Recharts展示实时性能趋势
 */
export function PerformanceChart() {
  const [activeChart, setActiveChart] = useState<
    'throughput' | 'latency' | 'resource'
  >('throughput');
  const [realTimeData, setRealTimeData] = useState<
    Array<{
      time: string;
      throughput: number;
      latency: number;
      cpuUsage: number;
      memoryUsage: number;
      networkIO: number;
    }>
  >([]);

  // 生成模拟实时数据
  useEffect(() => {
    const generateData = () => {
      const now = Date.now();
      const data = [];

      for (let i = 29; i >= 0; i--) {
        const timestamp = now - i * 1000;
        data.push({
          time: new Date(timestamp).toLocaleTimeString('zh-CN', {
            hour12: false,
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
          }),
          throughput: Math.floor(
            PERFORMANCE_METRICS.THROUGHPUT * (0.8 + Math.random() * 0.4)
          ),
          latency: Math.floor(
            PERFORMANCE_METRICS.ASK_LATENCY * (0.5 + Math.random() * 1.0)
          ),
          cpuUsage: Math.floor(20 + Math.random() * 30),
          memoryUsage: Math.floor(40 + Math.random() * 20),
          networkIO: Math.floor(1000 + Math.random() * 2000),
        });
      }

      return data;
    };

    // 初始化数据
    setRealTimeData(generateData());

    // 每秒更新数据
    const interval = setInterval(() => {
      setRealTimeData(prevData => {
        const newData = [...prevData.slice(1)];
        const lastTime = Date.now();

        newData.push({
          time: new Date(lastTime).toLocaleTimeString('zh-CN', {
            hour12: false,
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
          }),
          throughput: Math.floor(
            PERFORMANCE_METRICS.THROUGHPUT * (0.8 + Math.random() * 0.4)
          ),
          latency: Math.floor(
            PERFORMANCE_METRICS.ASK_LATENCY * (0.5 + Math.random() * 1.0)
          ),
          cpuUsage: Math.floor(20 + Math.random() * 30),
          memoryUsage: Math.floor(40 + Math.random() * 20),
          networkIO: Math.floor(1000 + Math.random() * 2000),
        });

        return newData;
      });
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  // 资源使用分布数据
  const resourceData = [
    { name: 'CPU', value: 25, color: '#3B82F6' },
    { name: '内存', value: 45, color: '#10B981' },
    { name: '网络I/O', value: 20, color: '#F59E0B' },
    { name: '磁盘I/O', value: 10, color: '#EF4444' },
  ];

  // 性能对比数据
  const comparisonData = [
    { name: 'CActor', throughput: 20000000, latency: 1.54, color: '#3B82F6' },
    { name: 'Akka', throughput: 12000000, latency: 3.2, color: '#10B981' },
    { name: 'Orleans', throughput: 8000000, latency: 5.1, color: '#F59E0B' },
    {
      name: 'Proto.Actor',
      throughput: 15000000,
      latency: 2.8,
      color: '#EF4444',
    },
  ];

  /**
   * 自定义Tooltip组件
   */
  const CustomTooltip = ({
    active,
    payload,
    label,
  }: {
    active?: boolean;
    payload?: Array<{
      name: string;
      value: number;
      color: string;
      dataKey: string;
    }>;
    label?: string;
  }) => {
    if (active && payload && payload.length) {
      return (
        <div className="bg-card border rounded-lg p-3 shadow-lg">
          <p className="text-sm font-medium mb-2">{`时间: ${label}`}</p>
          {payload.map((entry, index: number) => (
            <p key={index} className="text-sm" style={{ color: entry.color }}>
              {`${entry.name}: ${entry.value.toLocaleString()}`}
              {entry.dataKey === 'throughput' && ' msg/s'}
              {entry.dataKey === 'latency' && ' ns'}
              {(entry.dataKey === 'cpuUsage' ||
                entry.dataKey === 'memoryUsage') &&
                '%'}
              {entry.dataKey === 'networkIO' && ' MB/s'}
            </p>
          ))}
        </div>
      );
    }
    return null;
  };

  return (
    <section className="py-16">
      <div className="container">
        <div className="text-center mb-12">
          <h2 className="text-3xl font-bold mb-4">实时性能监控</h2>
          <p className="text-lg text-muted-foreground">
            实时监控CActor的性能指标和资源使用情况
          </p>
        </div>

        {/* 图表切换按钮 */}
        <div className="flex justify-center mb-8">
          <div className="inline-flex rounded-lg border p-1">
            <Button
              variant={activeChart === 'throughput' ? 'default' : 'ghost'}
              size="sm"
              onClick={() => setActiveChart('throughput')}
              className="rounded-md"
            >
              <TrendingUp className="mr-2 h-4 w-4" />
              吞吐量
            </Button>
            <Button
              variant={activeChart === 'latency' ? 'default' : 'ghost'}
              size="sm"
              onClick={() => setActiveChart('latency')}
              className="rounded-md"
            >
              <Clock className="mr-2 h-4 w-4" />
              延迟
            </Button>
            <Button
              variant={activeChart === 'resource' ? 'default' : 'ghost'}
              size="sm"
              onClick={() => setActiveChart('resource')}
              className="rounded-md"
            >
              <Activity className="mr-2 h-4 w-4" />
              资源
            </Button>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 主图表区域 */}
          <div className="lg:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  {activeChart === 'throughput' && (
                    <>
                      <TrendingUp className="h-5 w-5 text-blue-600" />
                      <span>消息吞吐量趋势</span>
                      <Badge variant="secondary">实时</Badge>
                    </>
                  )}
                  {activeChart === 'latency' && (
                    <>
                      <Clock className="h-5 w-5 text-green-600" />
                      <span>响应延迟趋势</span>
                      <Badge variant="secondary">实时</Badge>
                    </>
                  )}
                  {activeChart === 'resource' && (
                    <>
                      <Activity className="h-5 w-5 text-purple-600" />
                      <span>资源使用情况</span>
                      <Badge variant="secondary">实时</Badge>
                    </>
                  )}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-80">
                  {realTimeData.length > 0 && activeChart === 'throughput' && (
                    <ResponsiveContainer width="100%" height="100%">
                      <AreaChart data={realTimeData}>
                        <defs>
                          <linearGradient
                            id="throughputGradient"
                            x1="0"
                            y1="0"
                            x2="0"
                            y2="1"
                          >
                            <stop
                              offset="5%"
                              stopColor="#3B82F6"
                              stopOpacity={0.3}
                            />
                            <stop
                              offset="95%"
                              stopColor="#3B82F6"
                              stopOpacity={0}
                            />
                          </linearGradient>
                        </defs>
                        <CartesianGrid
                          strokeDasharray="3 3"
                          className="opacity-30"
                        />
                        <XAxis
                          dataKey="time"
                          tick={{ fontSize: 12 }}
                          interval="preserveStartEnd"
                        />
                        <YAxis
                          tick={{ fontSize: 12 }}
                          tickFormatter={value =>
                            `${(value / 1000000).toFixed(1)}M`
                          }
                        />
                        <Tooltip content={<CustomTooltip />} />
                        <Area
                          type="monotone"
                          dataKey="throughput"
                          stroke="#3B82F6"
                          strokeWidth={2}
                          fill="url(#throughputGradient)"
                          name="吞吐量"
                        />
                      </AreaChart>
                    </ResponsiveContainer>
                  )}

                  {realTimeData.length > 0 && activeChart === 'latency' && (
                    <ResponsiveContainer width="100%" height="100%">
                      <LineChart data={realTimeData}>
                        <CartesianGrid
                          strokeDasharray="3 3"
                          className="opacity-30"
                        />
                        <XAxis
                          dataKey="time"
                          tick={{ fontSize: 12 }}
                          interval="preserveStartEnd"
                        />
                        <YAxis
                          tick={{ fontSize: 12 }}
                          tickFormatter={value =>
                            `${(value / 1000).toFixed(1)}μs`
                          }
                        />
                        <Tooltip content={<CustomTooltip />} />
                        <Line
                          type="monotone"
                          dataKey="latency"
                          stroke="#10B981"
                          strokeWidth={2}
                          dot={{ fill: '#10B981', strokeWidth: 2, r: 3 }}
                          name="延迟"
                        />
                      </LineChart>
                    </ResponsiveContainer>
                  )}

                  {realTimeData.length > 0 && activeChart === 'resource' && (
                    <ResponsiveContainer width="100%" height="100%">
                      <LineChart data={realTimeData}>
                        <CartesianGrid
                          strokeDasharray="3 3"
                          className="opacity-30"
                        />
                        <XAxis
                          dataKey="time"
                          tick={{ fontSize: 12 }}
                          interval="preserveStartEnd"
                        />
                        <YAxis
                          tick={{ fontSize: 12 }}
                          tickFormatter={value => `${value}%`}
                        />
                        <Tooltip content={<CustomTooltip />} />
                        <Line
                          type="monotone"
                          dataKey="cpuUsage"
                          stroke="#3B82F6"
                          strokeWidth={2}
                          name="CPU使用率"
                        />
                        <Line
                          type="monotone"
                          dataKey="memoryUsage"
                          stroke="#10B981"
                          strokeWidth={2}
                          name="内存使用率"
                        />
                      </LineChart>
                    </ResponsiveContainer>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 侧边栏统计 */}
          <div className="space-y-6">
            {/* 实时指标 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Zap className="h-5 w-5 text-orange-600" />
                  <span>实时指标</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">
                    当前吞吐量
                  </span>
                  <span className="font-semibold">
                    {realTimeData.length > 0 &&
                      `${(realTimeData[realTimeData.length - 1]?.throughput / 1000000).toFixed(1)}M msg/s`}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">
                    当前延迟
                  </span>
                  <span className="font-semibold">
                    {realTimeData.length > 0 &&
                      `${(realTimeData[realTimeData.length - 1]?.latency / 1000).toFixed(1)}μs`}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">
                    CPU使用率
                  </span>
                  <span className="font-semibold">
                    {realTimeData.length > 0 &&
                      `${realTimeData[realTimeData.length - 1]?.cpuUsage}%`}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">
                    内存使用率
                  </span>
                  <span className="font-semibold">
                    {realTimeData.length > 0 &&
                      `${realTimeData[realTimeData.length - 1]?.memoryUsage}%`}
                  </span>
                </div>
              </CardContent>
            </Card>

            {/* 资源分布 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <PieChartIcon className="h-5 w-5 text-purple-600" />
                  <span>资源分布</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-48">
                  {resourceData.length > 0 && (
                    <ResponsiveContainer width="100%" height="100%">
                      <PieChart>
                        <Pie
                          data={resourceData}
                          cx="50%"
                          cy="50%"
                          innerRadius={40}
                          outerRadius={80}
                          paddingAngle={5}
                          dataKey="value"
                        >
                          {resourceData.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.color} />
                          ))}
                        </Pie>
                        <Tooltip formatter={value => [`${value}%`, '使用率']} />
                      </PieChart>
                    </ResponsiveContainer>
                  )}
                </div>
                <div className="grid grid-cols-2 gap-2 mt-4">
                  {resourceData.map(item => (
                    <div
                      key={item.name}
                      className="flex items-center space-x-2"
                    >
                      <div
                        className="w-3 h-3 rounded-full"
                        style={{ backgroundColor: item.color }}
                      />
                      <span className="text-sm">{item.name}</span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* 性能对比 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <BarChart3 className="h-5 w-5 text-green-600" />
                  <span>框架对比</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {comparisonData.map(item => (
                    <div key={item.name} className="space-y-1">
                      <div className="flex justify-between text-sm">
                        <span>{item.name}</span>
                        <span className="font-semibold">
                          {(item.throughput / 1000000).toFixed(1)}M
                        </span>
                      </div>
                      <div className="w-full bg-muted rounded-full h-2">
                        <div
                          className="h-2 rounded-full transition-all duration-1000"
                          style={{
                            width: `${(item.throughput / 20000000) * 100}%`,
                            backgroundColor: item.color,
                          }}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </section>
  );
}
